package casa.depesos.app.com.utils;

import androidx.fragment.app.FragmentActivity;

import com.support.toast.ToastUtil;

import casa.depesos.app.com.activity.AboutActivity;
import casa.depesos.app.com.activity.BaseActivity;
import casa.depesos.app.com.dlg.BaseDialogFragment;
import casa.depesos.app.com.dlg.UpdateDlg;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.UpdateBean;
import casa.depesos.app.com.http.req.UpdateReq;

public class Update {

    static UpdateDlg dlg = null;

    public void check(BaseActivity activity, boolean load, boolean showErr) {
        if (dlg != null) {
            return;
        }
        if (load) {
            activity.showLoading();
        }
        new UpdateReq(showErr).req(new ReqCallback<UpdateBean>() {
            @Override
            public void callback(boolean success, UpdateBean bean) {
                activity.hideLoading();
                if (success) {
                    tip(bean.info, activity, showErr);
                }
            }
        });
    }

    private void tip(casa.depesos.app.com.http.data.Update info, FragmentActivity activity, boolean showError) {
        try {
            boolean force = "1".equalsIgnoreCase(info.force);
            dlg = new UpdateDlg().setParam(force, info.url, activity instanceof AboutActivity ? 1 : 0)
                    .setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
                        @Override
                        public void onDismiss(boolean isOk, Object value) {
                            dlg = null;
                        }
                    });
            dlg.show(activity.getSupportFragmentManager(), "");
        } catch (Throwable e) {
            e.printStackTrace();
            if (showError) {
                ToastUtil.showShortToast(activity, "No hay versión disponible para actualizar");
            }
        }
    }
}
